import { RouteRecordRaw } from 'vue-router'
let defualtRoute: any = null

export const addRouteList = (menuList: any[]): RouteRecordRaw[] => {
  const routeList: RouteRecordRaw[] = []
  //先加载所有的路由
  const allRouteList: RouteRecordRaw[] = []
  const filesRoute = require.context('../router/main', true, /\.ts/)
  filesRoute.keys().forEach((path) => {
    const route = require('../router/main' + path.split('.')[1])
    allRouteList.push(route.default)
  })
  if (!menuList) {
    return routeList
  }
  //根据角色菜单动态生产路由数组
  const recursionGetRote = (menuList: any[]) => {
    for (const menu of menuList) {
      if (menu.type == 2) {
        const route = allRouteList.find((r) => {
          return r.path == menu.url
        })
        if (route) routeList.push(route)
        if (!defualtRoute) defualtRoute = route
      } else {
        recursionGetRote(menu.children)
      }
    }
  }
  recursionGetRote(menuList)
  return routeList
}

export function getbreadcrumbList(menuList: any[], routePath: string): any {
  const arr = []
  for (const menu of menuList) {
    if (menu.type == 1) {
      const currentMenu = getbreadcrumbList(menu.children, routePath)
      if (currentMenu) {
        arr.push({ name: menu.name })
        arr.push({ name: currentMenu.name })
        return arr
      }
    } else if (menu.type == 2 && menu.url == routePath) {
      return menu
    }
  }
}

export function getCurrentRote(menuList: any[], routePath: string): any {
  for (const menu of menuList) {
    if (menu.type == 1) {
      const currentMenu = getCurrentRote(menu.children, routePath)
      if (currentMenu) {
        return currentMenu
      }
    } else if (menu.type == 2 && menu.url == routePath) {
      return menu
    }
  }
}
//递归获取到菜单的叶子节点
export function getCurrentLeaf(menuList: any[]): number[] {
  const leafList: number[] = []
  const recursionLeaf = (menuList: any) => {
    for (const menuListElement of menuList) {
      if (menuListElement.children) {
        recursionLeaf(menuListElement.children)
      } else {
        leafList.push(menuListElement.id)
      }
    }
  }
  for (const key of menuList) {
    if (key.children) {
      recursionLeaf(key.children)
    } else {
      leafList.push(key.id)
    }
  }
  return leafList
}
export { defualtRoute }
